function importSMTPClasses() {
  try {
    importClass(java.net.Socket);
    importClass(java.io.BufferedReader);
    importClass(java.io.InputStreamReader);
    importClass(java.io.PrintWriter);
    importClass(java.io.OutputStreamWriter);
    importClass(java.util.Base64);
    importClass(javax.net.ssl.SSLSocketFactory);
    return true;
  } catch (e) {
    console.error("[nodemailer|19|context: importSMTPClasses()]", "导入 Java 类失败:", e);
    return false;
  }
}
var javaClassesImported = importSMTPClasses();
function createTransport(transportOptions) {
  var transportConfig = config || {};
  return {
    sendMail: function sendMail(mailOptions, callback) {
      var promise = new Promise(function (resolve, reject) {
        try {
          var readResponse = function readResponse() {
            var response = reader.readLine();
            if (response === null) {
              throw new Error("SMTP连接意外中断");
            }
            console.log("[nodemailer|101|context: createTransport() -> sendMail -> promise -> readResponse]", "[SMTP] 收到响应:", response);
            return response;
          };
          var sendCommand = function sendCommand(command) {
            console.log("[nodemailer|107|context: createTransport() -> sendMail -> promise -> sendCommand]", "[SMTP] 发送命令: " + command);
            writer.println(command);
            return readResponse();
          };
          var base64Encode = function base64Encode(str) {
            var bytes = java.lang.String(str).getBytes("UTF-8");
            return android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP);
          };
          if (!javaClassesImported) {
            throw new Error("无法导入 Java 类，无法使用 Socket 实现 SMTP 通信");
          }
          console.log("[nodemailer|52|context: createTransport() -> sendMail -> promise]", "[本地 nodemailer] 准备发送邮件");
          console.log("[nodemailer|53|context: createTransport() -> sendMail -> promise]", "[本地 nodemailer] 配置:", JSON.stringify(transportConfig));
          console.log("[nodemailer|54|context: createTransport() -> sendMail -> promise]", "[本地 nodemailer] 邮件选项:", JSON.stringify(mailOptions));
          var host = transportConfig.host || "smtp.qq.com";
          var port = parseInt(transportOptions.port || 465, 10);
          var secure = true;
          var tlsOptions = {
            servername: host,
            minVersion: "TLSv1.2",
            rejectUnauthorized: true
          };
          var auth = transportConfig.auth || {};
          var user = auth.user || "";
          var pass = auth.pass || "";
          var from = mailOptions.from || user;
          var to = mailOptions.to || "";
          var subject = mailOptions.subject || "";
          var text = mailOptions.text || "";
          var socket;
          if (secure) {
            var sslSocketFactory = javax.net.ssl.SSLSocketFactory.getDefault();
            socket = sslSocketFactory.createSocket(host, port.intValue(), null, tlsOptions);
            socket.setSoTimeout(30000);
          } else {
            socket = new java.net.Socket(host, port.intValue());
          }
          socket.setSoTimeout(30000);
          var reader = new java.io.BufferedReader(new java.io.InputStreamReader(socket.getInputStream(), "UTF-8"));
          var writer = new java.io.PrintWriter(new java.io.OutputStreamWriter(socket.getOutputStream(), "UTF-8"), true);
          try {
            var _readResponse = function _readResponse() {
              var response = reader.readLine();
              if (response === null) throw new Error("读取响应超时");
              return response;
            };
            var greeting = _readResponse();
            if (!greeting.startsWith("220")) {
              throw new Error("SMTP 服务器没有就绪: " + greeting);
            }
            var ehloResponse = sendCommand("EHLO");
            if (!ehloResponse.startsWith("250")) {
              console.warn("[nodemailer|129|context: createTransport() -> sendMail -> promise]", "EHLO命令返回非预期响应，尝试HELO命令");
              ehloResponse = sendCommand("HELO");
              if (!ehloResponse.startsWith("250")) {
                throw new Error("HELO命令失败: " + ehloResponse);
              }
            }
            if (secure) {
              socket.setEnabledProtocols(["TLSv1.2"]);
              socket.setEnabledCipherSuites(["TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", "TLS_RSA_WITH_AES_128_CBC_SHA"]);
            }
            var ehloLineCount = 0;
            var maxEhloLines = 10;
            while (ehloResponse && ehloResponse.startsWith("250-") && ehloLineCount < maxEhloLines) {
              ehloLineCount++;
              console.log("[nodemailer|151|context: createTransport() -> sendMail -> promise]", "[SMTP] 收到多行响应:", ehloResponse);
              ehloResponse = _readResponse();
            }
            if (ehloLineCount >= maxEhloLines) {
              console.warn("[nodemailer|155|context: createTransport() -> sendMail -> promise]", "达到EHLO响应最大行数限制");
            }
            var overallTimeout = setTimeout(function () {
              throw new Error("总操作超时（60秒）");
            }, 60000);
            clearTimeout(overallTimeout);
            if (user && pass) {
              var authResponse = sendCommand("AUTH LOGIN");
              if (!authResponse.startsWith("334")) {
                throw new Error("AUTH LOGIN 命令失败: " + authResponse);
              }
              var userResponse = sendCommand(base64Encode(user));
              if (!userResponse.startsWith("334")) {
                throw new Error("用户名认证失败: " + userResponse);
              }
              var passResponse = sendCommand(base64Encode(pass));
              if (!passResponse.startsWith("235")) {
                throw new Error("密码认证失败: " + passResponse);
              }
            }
            var mailFromResponse = sendCommand("MAIL FROM:<" + from + ">");
            if (!mailFromResponse.startsWith("250")) {
              throw new Error("MAIL FROM 命令失败: " + mailFromResponse);
            }
            var rcptToResponse = sendCommand("RCPT TO:<" + to + ">");
            if (!rcptToResponse.startsWith("250")) {
              throw new Error("RCPT TO 命令失败: " + rcptToResponse);
            }
            var dataResponse = sendCommand("DATA");
            if (!dataResponse.startsWith("354")) {
              throw new Error("DATA 命令失败: " + dataResponse);
            }
            var now = new Date();
            var date = now.toUTCString();
            writer.println("From: " + from);
            writer.println("To: " + to);
            writer.println("Subject: " + subject);
            writer.println("Date: " + date);
            writer.println("MIME-Version: 1.0");
            writer.println("Content-Type: text/plain; charset=UTF-8");
            writer.println("Content-Transfer-Encoding: 7bit");
            writer.println("");
            writer.println(text);
            var endResponse = sendCommand(".");
            if (!endResponse.startsWith("250")) {
              throw new Error("邮件发送失败: " + endResponse);
            }
            sendCommand("QUIT");
            var info = {
              messageId: "<" + Date.now() + Math.random().toString(36).substring(2, 15) + "@" + host + ">",
              response: endResponse,
              accepted: [to],
              rejected: [],
              pending: [],
              envelope: {
                from: from,
                to: [to]
              }
            };
            console.log("[nodemailer|250|context: createTransport() -> sendMail -> promise]", "[本地 nodemailer] 邮件已发送:", info.messageId);
            resolve(info);
            if (typeof callback === 'function') {
              callback(null, info);
            }
          } finally {
            try {
              if (writer) writer.close();
              if (reader) reader.close();
              if (socket) socket.close();
            } catch (e) {
              console.error("[nodemailer|266|context: createTransport() -> sendMail -> promise]", "关闭连接时出错:", e);
            }
          }
        } catch (error) {
          console.log("[nodemailer|270|context: createTransport() -> sendMail -> promise]", "[本地 nodemailer] 发送失败:", error);
          reject(error);
          if (typeof callback === 'function') {
            callback(error);
          }
        }
      });
      if (typeof callback !== 'function') {
        return promise;
      }
    }
  };
}
module.exports = {
  createTransport: createTransport
};